// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: hyuan

#include "coin2/exchange/kucoin/api_util/rate_tracker.h"

#include <algorithm>
#include <sstream>
#include <string>

#include <boost/algorithm/string/replace.hpp>
#include <glog/logging.h>

#include "coin2/base/proto_util.h"
#include "coin2/exchange/base/order/rate_config.h"

namespace coin2::exchange::kucoin::api_util {

constexpr auto EXAMPLE_SPOT_KUCOIN = R"(
"connection_config": {
  "key_filepath": "/home/ec2-user/config/trade/xunke18/kucoin/trade_key.json",
  "rate_limit_info": {
    "spot_kucoin": {
      "list_order": {
        "secs": 3,
        "reqs": 30
      },
      "fill_order": {
        "secs": 3,
        "reqs": 9
      },
      "place_order": {
        "secs": 3,
        "reqs": 45
      },
      "cancel_order": {
        "secs": 3,
        "reqs": 60
      }
    }
  }
},)";

constexpr auto EXAMPLE_FUTURES_KUCOIN = R"(
"connection_config": {
  "key_filepath": "/home/ec2-user/config/trade/xunke18/kucoin/trade_key.json",
  "rate_limit_info": {
    "futures_kucoin": {
      "account": {
        "secs": 3,
        "reqs": 30
      },
      "position": {
        "secs": 3,
        "reqs": 9
      },
      "list_order": {
        "secs": 3,
        "reqs": 30
      },
      "fill_order": {
        "secs": 3,
        "reqs": 9
      },
      "place_order": {
        "secs": 3,
        "reqs": 30
      },
      "cancel_order": {
        "secs": 3,
        "reqs": 40
      }
    }
  }
},)";

template <class RateTracker>
void CheckFail(RateTracker&& rate_tracker, bool check_result) {
  if (!check_result) {
    LOG(INFO) << "Hit rate limit on [" << rate_tracker->GetName() << "]";
  }
}

KucoinRateTracker::KucoinRateTracker(
    const MarketExchangeApi& mea,
    const coin2::exchange::order::OrderConnectionConfig& cfg) {
  using RateConfig = coin2::exchange::base::order::RateConfig;
  if (mea.market == coin::proto::MarketType::Spot) {
    RateLimitInfoSpotKucoin rate_config;
    RateConfig::Get()->GetConfig(mea, cfg, &rate_config);
    InitRateTracker(&rate_config, mea.String(), EXAMPLE_SPOT_KUCOIN);
  } else if (mea.market == coin::proto::MarketType::Futures) {
    RateLimitInfoFuturesKucoin rate_config;
    RateConfig::Get()->GetConfig(mea, cfg, &rate_config);
    InitRateTracker(&rate_config, mea.String(), EXAMPLE_FUTURES_KUCOIN);
  } else {
    CHECK(false) << "unsupported mea: " << mea.String();
  }
}

void KucoinRateTracker::InitRateTracker(
    RateLimitInfoSpotKucoin* rate_config,
    std::string_view mea_str,
    std::string_view example) {
  if (!rate_config || !rate_config->has_list_order() || !rate_config->has_fill_order() ||
      !rate_config->has_place_order() || !rate_config->has_cancel_order()) {
    coin2::exchange::base::order::RateConfig::CheckFail(mea_str, example);
  }

  const auto& list_order = rate_config->list_order();
  const auto& fill_order = rate_config->fill_order();
  const auto& place_order = rate_config->place_order();
  const auto& cancel_order = rate_config->cancel_order();
  LOG(INFO) << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
            << "\nOG request rate was set as below:\n"
            << "\nlist_order: [" << list_order.reqs() << "(reqs)/" << list_order.secs() << "(secs)]"
            << "\nfill_order: [" << fill_order.reqs() << "(reqs)/" << fill_order.secs() << "(secs)]"
            << "\nplace_order: [" << place_order.reqs() << "(reqs)/" << place_order.secs()
            << "(secs)]"
            << "\ncancel_order: [" << cancel_order.reqs() << "(reqs)/" << cancel_order.secs()
            << "(secs)]"
            << "\n\nOr you can configure customized rate in driver config. For example: " << example
            << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";

  rate_tracker_listorder_ =
      std::make_unique<FixedWindowRateTracker>(list_order.secs() * 1'000'000'000LL);
  rate_tracker_listorder_->SetRateLimitInfo(list_order.reqs(), list_order.reqs());
  rate_tracker_listorder_->SetName("kucoin_rate_tracker_list_order(1 min)");

  rate_tracker_fillorder_ =
      std::make_unique<FixedWindowRateTracker>(fill_order.secs() * 1'000'000'000LL);
  rate_tracker_fillorder_->SetRateLimitInfo(fill_order.reqs(), fill_order.reqs());
  rate_tracker_fillorder_->SetName("kucoin_rate_tracker_fill_order(1 min)");

  rate_tracker_placeorder_ =
      std::make_unique<FixedWindowRateTracker>(place_order.secs() * 1'000'000'000LL);
  rate_tracker_placeorder_->SetRateLimitInfo(place_order.reqs(), place_order.reqs());
  rate_tracker_placeorder_->SetName("kucoin_rate_tracker_place_order(1 min)");

  rate_tracker_cancelorder_ =
      std::make_unique<FixedWindowRateTracker>(cancel_order.secs() * 1'000'000'000LL);
  rate_tracker_cancelorder_->SetRateLimitInfo(cancel_order.reqs(), cancel_order.reqs());
  rate_tracker_cancelorder_->SetName("kucoin_rate_tracker_cancel_order(1 min)");

  rate_limit_report_writer_ = std::make_unique<RateLimitReportWriter>();
  rate_limit_report_writer_->SetRateLimitInfoString(rate_config);
}

void KucoinRateTracker::InitRateTracker(
    RateLimitInfoFuturesKucoin* rate_config,
    std::string_view mea_str,
    std::string_view example) {
  if (!rate_config || !rate_config->has_account() || !rate_config->has_position() ||
      !rate_config->has_list_order() || !rate_config->has_fill_order() ||
      !rate_config->has_place_order() || !rate_config->has_cancel_order()) {
    coin2::exchange::base::order::RateConfig::CheckFail(mea_str, example);
  }

  const auto& account = rate_config->account();
  const auto& position = rate_config->position();
  const auto& list_order = rate_config->list_order();
  const auto& fill_order = rate_config->fill_order();
  const auto& place_order = rate_config->place_order();
  const auto& cancel_order = rate_config->cancel_order();
  LOG(INFO) << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
            << "\nOG request rate was set as below:\n"
            << "\naccount: [" << account.reqs() << "(reqs)/" << account.secs() << "(secs)]"
            << "\nposition: [" << position.reqs() << "(reqs)/" << position.secs() << "(secs)]"
            << "\nlist_order: [" << list_order.reqs() << "(reqs)/" << list_order.secs() << "(secs)]"
            << "\nfill_order: [" << fill_order.reqs() << "(reqs)/" << fill_order.secs() << "(secs)]"
            << "\nplace_order: [" << place_order.reqs() << "(reqs)/" << place_order.secs()
            << "(secs)]"
            << "\ncancel_order: [" << cancel_order.reqs() << "(reqs)/" << cancel_order.secs()
            << "(secs)]"
            << "\n\nOr you can configure customized rate in driver config. For example: " << example
            << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";

  rate_tracker_account_ =
      std::make_unique<FixedWindowRateTracker>(account.secs() * 1'000'000'000LL);
  rate_tracker_account_->SetRateLimitInfo(account.reqs(), account.reqs());
  rate_tracker_account_->SetName("kucoin_rate_tracker_account(1 min)");

  rate_tracker_position_ =
      std::make_unique<FixedWindowRateTracker>(position.secs() * 1'000'000'000LL);
  rate_tracker_position_->SetRateLimitInfo(position.reqs(), position.reqs());
  rate_tracker_position_->SetName("kucoin_rate_tracker_position(1 min)");

  rate_tracker_listorder_ =
      std::make_unique<FixedWindowRateTracker>(list_order.secs() * 1'000'000'000LL);
  rate_tracker_listorder_->SetRateLimitInfo(list_order.reqs(), list_order.reqs());
  rate_tracker_listorder_->SetName("kucoin_rate_tracker_list_order(1 min)");

  rate_tracker_fillorder_ =
      std::make_unique<FixedWindowRateTracker>(fill_order.secs() * 1'000'000'000LL);
  rate_tracker_fillorder_->SetRateLimitInfo(fill_order.reqs(), fill_order.reqs());
  rate_tracker_fillorder_->SetName("kucoin_rate_tracker_fill_order(1 min)");

  rate_tracker_placeorder_ =
      std::make_unique<FixedWindowRateTracker>(place_order.secs() * 1'000'000'000LL);
  rate_tracker_placeorder_->SetRateLimitInfo(place_order.reqs(), place_order.reqs());
  rate_tracker_placeorder_->SetName("kucoin_rate_tracker_place_order(1 min)");

  rate_tracker_cancelorder_ =
      std::make_unique<FixedWindowRateTracker>(cancel_order.secs() * 1'000'000'000LL);
  rate_tracker_cancelorder_->SetRateLimitInfo(cancel_order.reqs(), cancel_order.reqs());
  rate_tracker_cancelorder_->SetName("kucoin_rate_tracker_cancel_order(1 min)");

  rate_limit_report_writer_ = std::make_unique<RateLimitReportWriter>();
  rate_limit_report_writer_->SetRateLimitInfoString(rate_config);
}

bool KucoinRateTracker::HasEnoughRateLimit(
    int64_t timestamp,
    ActionType action_type,
    QueryType query_type) {
  if (CheckEnableTime(timestamp, action_type, query_type) &&
      CheckRateLimit(timestamp, action_type, query_type)) {
    return true;
  }

  rate_limit_report_writer_->SetHitRateLimit(timestamp, action_type);
  return false;
}

void KucoinRateTracker::Push(
    int32_t num_reqs,
    int64_t timestamp,
    ActionType action_type,
    QueryType query_type) {
  if (action_type == ActionType::PLACE) {
    if (rate_tracker_placeorder_) {
      rate_tracker_placeorder_->Push(num_reqs, timestamp);
    }
  } else if (action_type == ActionType::CANCEL) {
    if (rate_tracker_cancelorder_) {
      rate_tracker_cancelorder_->Push(num_reqs, timestamp);
    }
  } else if (action_type == ActionType::QUERY) {
    if (query_type == QueryType::BALANCE) {
      if (rate_tracker_account_) {
        rate_tracker_account_->Push(num_reqs, timestamp);
      }
    } else if (query_type == QueryType::POSITION) {
      if (rate_tracker_position_) {
        rate_tracker_position_->Push(num_reqs, timestamp);
      }
    } else if (query_type == QueryType::OPEN_ORDER) {
      if (rate_tracker_listorder_) {
        rate_tracker_listorder_->Push(num_reqs, timestamp);
      }
    } else if (query_type == QueryType::HIST_ORDER) {
      if (rate_tracker_listorder_) {
        rate_tracker_listorder_->Push(num_reqs, timestamp);
      }
    } else if (query_type == QueryType::FILL_ORDER) {
      if (rate_tracker_fillorder_) {
        rate_tracker_fillorder_->Push(num_reqs, timestamp);
      }
    } else {
      return;
    }
  } else {
    return;
  }
}

void KucoinRateTracker::SetRateLimitInfoString(const google::protobuf::Message* message) {
  if (!rate_limit_report_writer_) {
    return;
  }
  rate_limit_report_writer_->SetRateLimitInfoString(message);
}

void KucoinRateTracker::WriteRateLimitReportMessage(OrderLoggerCB callback) {
  if (!callback) {
    return;
  }
  rate_limit_report_writer_->Write(callback);
}

double KucoinRateTracker::GetMaxRateUsedRatio(int64_t timestamp, ActionType action_type) {
  switch (action_type) {
    case ActionType::PLACE: {
      return GetMaxRateUsedRatio(rate_tracker_placeorder_, timestamp);
    }
    case ActionType::CANCEL: {
      return GetMaxRateUsedRatio(rate_tracker_cancelorder_, timestamp);
    }
    case ActionType::QUERY: {
      double account_rate_used_ratios = GetMaxRateUsedRatio(rate_tracker_account_, timestamp);
      double position_rate_used_ratios = GetMaxRateUsedRatio(rate_tracker_position_, timestamp);
      double listorder_rate_used_ratios = GetMaxRateUsedRatio(rate_tracker_listorder_, timestamp);
      double fillorder_rate_used_ratios = GetMaxRateUsedRatio(rate_tracker_fillorder_, timestamp);
      return std::max(
          std::max(account_rate_used_ratios, position_rate_used_ratios),
          std::max(listorder_rate_used_ratios, fillorder_rate_used_ratios));
    }
    default: {
      // shouldn't reached here
      LOG(ERROR) << "ops~ something is wrong, action_type=" << action_type;
      return 0.;
    }
  }
}

bool KucoinRateTracker::CheckEnableTime(
    int64_t timestamp,
    ActionType action_type,
    QueryType query_type) {
  if (timestamp >= enable_time_) {
    return true;
  }

  LOG_EVERY_N(WARNING, 50) << "Hit api temporary disabled until " << enable_time_ << ", "
                           << action_type << ", " << query_type;
  return false;
}

bool KucoinRateTracker::CheckRateLimit(
    int64_t timestamp,
    ActionType action_type,
    QueryType query_type) {
  bool ret = true;
  if (action_type == ActionType::PLACE) {
    if (rate_tracker_placeorder_) {
      ret = rate_tracker_placeorder_->GetRemaining(timestamp) > 2;
      CheckFail(rate_tracker_placeorder_, ret);
    }
  } else if (action_type == ActionType::CANCEL) {
    if (rate_tracker_cancelorder_) {
      ret = rate_tracker_cancelorder_->GetRemaining(timestamp) > 2;
      CheckFail(rate_tracker_cancelorder_, ret);
    }
  } else if (action_type == ActionType::QUERY) {
    if (query_type == QueryType::BALANCE) {
      if (rate_tracker_account_) {
        ret = (rate_tracker_account_->GetRemaining(timestamp) > 2);
        CheckFail(rate_tracker_account_, ret);
      }
    } else if (query_type == QueryType::POSITION) {
      if (rate_tracker_position_) {
        ret = (rate_tracker_position_->GetRemaining(timestamp) > 2);
        CheckFail(rate_tracker_position_, ret);
      }
    } else if (query_type == QueryType::OPEN_ORDER) {
      if (rate_tracker_listorder_) {
        ret = (rate_tracker_listorder_->GetRemaining(timestamp) > 2);
        CheckFail(rate_tracker_listorder_, ret);
      }
    } else if (query_type == QueryType::HIST_ORDER) {
      if (rate_tracker_listorder_) {
        ret = (rate_tracker_listorder_->GetRemaining(timestamp) > 2);
        CheckFail(rate_tracker_listorder_, ret);
      }
    } else if (query_type == QueryType::FILL_ORDER) {
      if (rate_tracker_fillorder_) {
        ret = (rate_tracker_fillorder_->GetRemaining(timestamp) > 2);
        CheckFail(rate_tracker_fillorder_, ret);
      }
    }
  }

  return ret;
}

}  // namespace coin2::exchange::kucoin::api_util
